#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //设置串口名（COM1）
    serial.setPortName("COM3");
    //设置波特率(115200)
    serial.setBaudRate(115200);
    //设置数据位(8)
    serial.setDataBits(QSerialPort::Data8);
    //设置没有奇偶校验位(无)
    serial.setParity(QSerialPort::NoParity);//oddParity,evenParity
    //设置停止位(1)
    serial.setStopBits(QSerialPort::OneStop);
    //设置没有流控制
    serial.setFlowControl(QSerialPort::NoFlowControl);
    //以可读写的方式打开串口
    serial.open(QIODevice::ReadWrite);
    QList<QSerialPortInfo> qSerialPortInfo = QSerialPortInfo::availablePorts();
    qDebug()<<qSerialPortInfo.back().portName();

    for (;!qSerialPortInfo.isEmpty();) {//扫描串口加入列表
        ui->cb_serialport->addItem(qSerialPortInfo.back().portName());
        qSerialPortInfo.pop_back();
    }


}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_bt_on_clicked()
{
    char parity_code='H'+'C'+'L'+'1'+'1';
    memset(sendBuffer,0,sizeof(sendBuffer));
    strcpy(sendBuffer,"HCL11");
    sendBuffer[strlen("HCL11")]=parity_code;
    sendBuffer[strlen("HCL11")+1]=':';
    serial.write(sendBuffer);

    buffer.clear();
    buffer=serial.readAll();
    qDebug()<<buffer.data();
    ui->plainTextEdit->setPlainText(ui->plainTextEdit->toPlainText()+buffer.data());

//    QByteArray *str=new  QByteArray("hello");
//    qDebug()<<str->data();
//    qDebug()<<str;
}

void MainWindow::on_bt_off_clicked()
{
    char parity_code='H'+'C'+'L'+'1'+'0';
    memset(sendBuffer,0,sizeof(sendBuffer));
    strcpy(sendBuffer,"HCL10");
    sendBuffer[strlen("HCL10")]=parity_code;
    sendBuffer[strlen("HCL10")+1]=':';
    //qDebug()<<sendBuffer;
    serial.write(sendBuffer);

    buffer.clear();
    buffer=serial.readAll();
    qDebug()<<buffer.data();
    ui->plainTextEdit->setPlainText(ui->plainTextEdit->toPlainText()+buffer.data());
}
